package com.lab.es.demo.xls;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.lab.es.demo.entity.Item;
import com.lab.es.demo.mapper.ItemMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ItemListener extends AnalysisEventListener<Item> {
    private static final int BATCH_COUNT = 3000;
    List<Item> list = new ArrayList<Item>();

    private ItemMapper itemMapper;

    public ItemListener(ItemMapper itemMapper) {
        this.itemMapper = itemMapper;
    }

    @Override
    public void invoke(Item data, AnalysisContext context) {
        //log.info("解析到一条数据:{}", JSON.toJSONString(data, SerializerFeature.PrettyFormat));
        list.add(data);

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        itemMapper.insertBatchSomeColumn(list);
        log.info("存储数据库成功！");
    }
}
